package Dao;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;

import pojo.User;

public class UserDao {
	//属性
	private File file = new File("user.json");
	private ObjectMapper om = new ObjectMapper();
	//单例模式
	private static UserDao UserDao = new UserDao();
	private UserDao() {}
	public static UserDao getInstance() {
		return UserDao;
	}
	
	public boolean add(User user) {
		ArrayList<User> users = new ArrayList<>();
		
		try {
			users = this.om.readValue(file, new TypeReference<List<User>>() {});
			for(User u:users) {
				if(u.getId().equals(user.getId())) {
					return false;
				}
			}
			users.add(user);
			om.writeValue(file, users);
			return true;
		} catch(MismatchedInputException e) {//文件为空
			users.add(user);
			try {
				om.writeValue(file, users);
				return true;
			} catch (IOException e1) {
				e1.printStackTrace();
				return false;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public User search(User user) {
		ArrayList<User> users = new ArrayList<>();
		
		try {
			users = this.om.readValue(file, new TypeReference<List<User>>() {});
			for(User u:users) {
				if(u.getId().equals(user.getId())) {
					return u;
				}
			}
			return null;
		} catch(MismatchedInputException e) {//文件为空
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		}		
		return null;
	}
	
	public ArrayList<User> list(){
		ArrayList<User> users = new ArrayList<>();
		
		try {
			users = this.om.readValue(file, new TypeReference<List<User>>() {});
			return users;
		}catch(MismatchedInputException e) {
			return users;
		}catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public boolean cover(User user) {
		if(user == null) return false;
		
		ArrayList<User> users;
		
		try {
			users = this.om.readValue(file, new TypeReference<List<User>>() {});
			
			for(int i=0;i<users.size();i++) {
				if(users.get(i).getId().equals(user.getId())) {
					users.set(i, user);
					om.writeValue(file, users);
					return true;
				}
			}
			
		}catch(MismatchedInputException e) {
			return false;
		}catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static void main(String[] args) {
		//测试，加数据
		UserDao userDao = UserDao.getInstance();
		System.out.println(userDao.add(new User("0", "0", false, null)));
		System.out.println(userDao.add(new User("1", "0", false, null)));
		System.out.println(userDao.add(new User("2", "0", false, null)));
		System.out.println(userDao.add(new User("3", "1", true, null)));
	}

}
